package org.leetcode.middle.leetcode129;

import org.leetcode.TreeNode;

public class Solution {
    int sum = 0;
    public int sumNumbers(TreeNode root) {
        dfs(root,0);
        return sum;
    }

    private void dfs(TreeNode root,int val){

        val = val*10+root.val;
        //判断root.left和root.right不等于null,而不是判断root==null。
        //是因为root==null，会使得叶子节点重复计算
        if (root.left==null && root.right==null){
            sum = sum+val;
            return;
        }
        if (root.left!=null) {
            dfs(root.left,val);
        }
        if (root.right!=null){
            dfs(root.right,val);
        }
    }
}
